package com.awspaass.user.apps.syncwechataddress;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.actionsoft.bpms.commons.database.ColumnMapRowMapper;
import com.actionsoft.bpms.schedule.IJob;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.ORGAPI;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.awspaas.user.apps.shhtaerospaceindustrial.util.CoreUtil;

public class test implements IJob {
	public static String readToString(String fileName) {
		String encoding = "UTF-8";
		File file = new File(fileName);
		Long filelength = file.length();
		byte[] filecontent = new byte[filelength.intValue()];
		try {
			FileInputStream in = new FileInputStream(file);
			in.read(filecontent);
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			return new String(filecontent, encoding);
		} catch (UnsupportedEncodingException e) {
			System.err.println("The OS does not support " + encoding);
			e.printStackTrace();
			return null;
		}
	}

	public static String getDepIdAwsByidwechat(String id_wechat, String companyid) {
		String depid = null;
		List<Map<String, Object>> departlist = null;
		try {
			String sql = "select * from BO_INFO_WECHAT_AWS where COMPANYIDAWS='" + companyid + "' and IDWECHAT = '"
					+ id_wechat + "'";
			departlist = DBSql.query(sql, new ColumnMapRowMapper(), new Object[] {});
			if (departlist.isEmpty() || departlist == null) {
				System.out.println("NO DEPARTMENT");
				return null;
			}
			Map<String, Object> dep = departlist.get(0);
			depid = CoreUtil.objToStr(dep.get("DEPIDAWS"));
		} catch (Exception e) {
			e.printStackTrace();

		}
		return depid;
	}

	public void updateUserTable(List<WxUserInfo> wechatUserList, String companywechatid, long timeFlag) {
		for (WxUserInfo user : wechatUserList) {
			String userId = user.getUserId();
			String depId = user.getDepartmentId();
			String userName = user.getName();
			String mobile = user.getMobile();

			String queryUserSql = "SELECT * from WECHAT_USER WHERE USERID='" + userId + "' AND DEPID ='"+depId+"' AND COMPANYID='"+companywechatid+"'";
			String updateUserSql = "";

			List<Map<String, Object>> userWechatList = DBSql.query(queryUserSql, new ColumnMapRowMapper(),
					new Object[] {});
			if (userWechatList.size() > 0) {
				Map<String, Object> userWechat = userWechatList.get(0);
				String userIdWechat = CoreUtil.objToStr(userWechat.get("USERID"));
				String depIdWechat = CoreUtil.objToStr(userWechat.get("DEPID"));
				String userNameWechat = CoreUtil.objToStr(userWechat.get("USERNAME"));
				String MOBILE = CoreUtil.objToStr(userWechat.get("MOBILE"));
				if (!userNameWechat.equals(userName)|| !MOBILE.equals(mobile)) {
					updateUserSql = "UPDATE WECHAT_USER SET USERNAME='" + userName
							+  "', MOBILE='" + mobile + "',TIMEFLAG=" + timeFlag
							+ ",STATUS='1'  WHERE USERID='" + userId + "' AND DEPID ='"+depId+"' AND COMPANYID='"+companywechatid+"'";
				} else {
					updateUserSql = "UPDATE WECHAT_USER SET TIMEFLAG=" + timeFlag + " WHERE USERID='"
							+ userId + "' AND DEPID ='"+depId+"' AND COMPANYID='"+companywechatid+"'";
				}
				DBSql.update(updateUserSql);
			} else {
				String insertUserSql = "INSERT INTO WECHAT_USER(USERID,DEPID,USERNAME,MOBILE,STATUS,COMPANYID,TIMEFLAG)VALUES(:USERID,:DEPID,:USERNAME,:MOBILE,:STATUS,:COMPANYID,:TIMEFLAG)";
				Map<String, Object> paraMap = new HashMap<>();
				paraMap.put("USERID", userId);
				paraMap.put("DEPID", depId);
				paraMap.put("USERNAME", userName);
				paraMap.put("MOBILE", mobile);
				paraMap.put("STATUS", "1");
				paraMap.put("COMPANYID", companywechatid);
				paraMap.put("TIMEFLAG", timeFlag);
				DBSql.update(insertUserSql, paraMap);
			}

		}
	}

	public void UpdateDepartments(List<Map<String, String>> dep_wechat, String companyid_aws, String companyid_wechat,
			long timeFlag) {

		/*
		 * System.out.println("微信部门数目："+dep_wechat.size()/3+" ，aws部门数目"+dep_aws.size());
		 * if(dep_wechat.size()/3<=dep_aws.size()) { return; }
		 */

		for (int i = 0; i < dep_wechat.size(); i++) {
			String id_wechat = dep_wechat.get(i).get("id");
			i++;
			String name_wechat = dep_wechat.get(i).get("name");
			i++;
			String parentid_wechat = dep_wechat.get(i).get("parentid");
			// System.out.println("微信部门ID:"+id_wechat);
			// System.out.println("微信部门名称："+name_wechat);
			// System.out.println("parentid_wechat"+parentid_wechat);
			String depQuerySql = "select * from BO_INFO_WECHAT_AWS t where t.conmpanyidwechat =  '" + companyid_wechat
					+ "'and t.idwechat = '" + id_wechat + "'";
			List<Map<String, Object>> depQueryList = DBSql.query(depQuerySql, new ColumnMapRowMapper(),
					new Object[] {});

			if (depQueryList == null) {
				System.out.println("depQuerySql Error!");
				return;
			}

			if (depQueryList.size() == 0) {
				String newDepId;
				String dep_p_id_aws = getDepIdAwsByidwechat(parentid_wechat, companyid_aws);
				if (("0").equals(parentid_wechat)) {
					newDepId = SDK.getORGAPI().createDepartment(companyid_aws, name_wechat, null, null, "0", null,
							null);
				} else {
					newDepId = SDK.getORGAPI().createDepartment(companyid_aws, name_wechat, null, null, dep_p_id_aws,
							null, null);
				}
				System.out.println("Insert" + name_wechat);
				String sql = "INSERT INTO BO_INFO_WECHAT_AWS  (DEPIDAWS,IDWECHAT,PARENTIDWECHAT,NAME,COMPANYIDAWS,CONMPANYIDWECHAT,PARENTIDAWS,TIMEFLAG,STATUS)VALUES(:DEPIDAWS,:IDWECHAT,:PARENTIDWECHAT,:NAME,:COMPANYIDAWS,:CONMPANYIDWECHAT,:PARENTIDAWS,:TIMEFLAG,:STATUS)";
				Map<String, Object> paraMap = new HashMap<>();
				paraMap.put("DEPIDAWS", newDepId);
				paraMap.put("IDWECHAT", id_wechat);
				paraMap.put("PARENTIDWECHAT", parentid_wechat);
				paraMap.put("NAME", name_wechat);
				paraMap.put("COMPANYIDAWS", companyid_aws);
				paraMap.put("CONMPANYIDWECHAT", companyid_wechat);
				paraMap.put("PARENTIDAWS", dep_p_id_aws);
				paraMap.put("TIMEFLAG", timeFlag);
				paraMap.put("STATUS", 1);
				DBSql.update(sql, paraMap);
			} else {
				Map<String, Object> dep = depQueryList.get(0);
				String dep_name_aws = CoreUtil.objToStr(dep.get("NAME"));
				String depidAws = CoreUtil.objToStr(dep.get("DEPIDAWS"));
				String updateSql = "";
				if (dep_name_aws.equals(name_wechat)) {
					updateSql = "update BO_INFO_WECHAT_AWS t set t.name='" + name_wechat + "',t.TIMEFLAG=" + timeFlag
							+ ",t.STATUS='0'" + " where t.companyidaws= '" + companyid_aws + "' and t.idwechat='"
							+ id_wechat + "'";
				} else {
					updateSql = "update BO_INFO_WECHAT_AWS t set t.name='" + name_wechat + "',t.TIMEFLAG=" + timeFlag
							+ ",t.STATUS='1'" + " where t.companyidaws= '" + companyid_aws + "' and t.idwechat='"
							+ id_wechat + "'";

					SDK.getORGAPI().updateDepartment(depidAws, name_wechat, ORGAPI.NO_UPDATE, ORGAPI.NO_UPDATE,
							ORGAPI.NO_UPDATE, ORGAPI.NO_UPDATE);

				}
				DBSql.update(updateSql);

			}
		}
	}

	public long getLatestTimeFlag() {
		long timeFlag = -1;
		String querySql = "select max(t.timeflag) as timeflag from BO_INFO_WECHAT_AWS t";
		List<Map<String, Object>> depQueryList = DBSql.query(querySql, new ColumnMapRowMapper(), new Object[] {});
		Map<String, Object> dep = depQueryList.get(0);
		timeFlag = CoreUtil.objToInt(dep.get("TIMEFLAG"));
		return timeFlag;
	}

	public void deleteUnRegisterDep(long lastTimeFlag, String companyid_wechat) {
		String queryUnDepSql = "select * from BO_INFO_WECHAT_AWS t where t.CONMPANYIDWECHAT='" + companyid_wechat
				+ "' and t.timeflag <" + lastTimeFlag;
		// System.out.println(queryUnDepSql);
		List<Map<String, Object>> depQueryList = DBSql.query(queryUnDepSql, new ColumnMapRowMapper(), new Object[] {});

		if (depQueryList == null) {
			System.out.println("depQuerySql Error!");
			return;
		}
		for (int i = 0; i < depQueryList.size(); i++) {
			Map<String, Object> dep = depQueryList.get(i);
			String depAwsId = CoreUtil.objToStr(dep.get("DEPIDAWS"));
			String companyAwdId = CoreUtil.objToStr(dep.get("COMPANYIDAWS"));
			String queryCountSql = "select * from UNREGISTERDEP t where t.DEPIDAWS ='" + depAwsId + "'";
			String insertUnSql = "insert into UNREGISTERDEP (DEPIDAWS,DEPCOMPANYIDAWS)VALUES(:DEPIDAWS,:DEPCOMPANYIDAWS)";
			List<Map<String, Object>> depUnDepList = DBSql.query(queryCountSql, new ColumnMapRowMapper(),
					new Object[] {});
			if (depUnDepList.size() > 0) {
				continue;
			} else {
				Map<String, Object> paraMap = new HashMap<>();
				paraMap.put("DEPIDAWS", depAwsId);
				paraMap.put("DEPCOMPANYIDAWS", companyAwdId);
				DBSql.update(insertUnSql, paraMap);
			}
		}
		String delSql = "delete from BO_INFO_WECHAT_AWS t where t.CONMPANYIDWECHAT='" + companyid_wechat
				+ "' and t.timeflag <" + lastTimeFlag;
		DBSql.update(delSql);
	}

	public void deleteUnRegisterUser(long lastTimeFlag, String companyid_wechat) {
		String queryUnDepSql = "select a.USERID,b.depidaws,b.companyidaws ,a.mobile,a.username from WECHAT_USER a, BO_INFO_WECHAT_AWS b where a.depid=b.idwechat and a.companyid=b.conmpanyidwechat and a.COMPANYID='" + companyid_wechat
				+ "' and a.timeflag <" + lastTimeFlag;
		// System.out.println(queryUnDepSql);
		List<Map<String, Object>> depQueryList = DBSql.query(queryUnDepSql, new ColumnMapRowMapper(), new Object[] {});

		if (depQueryList == null) {
			System.out.println("depQuerySql Error!");
			return;
		}
		for (int i = 0; i < depQueryList.size(); i++) {
			Map<String, Object> dep = depQueryList.get(i);
			String userId = CoreUtil.objToStr(dep.get("USERID"));
			String depidAws=CoreUtil.objToStr(dep.get("DEPIDAWS"));
			String companyIdAws=CoreUtil.objToStr(dep.get("COMPANYIDAWS"));
			String phone=CoreUtil.objToStr(dep.get("MOBILE"));
			String username=CoreUtil.objToStr(dep.get("USERNAME"));
			String queryCountSql = "select * from unregistereduser t where t.userid ='"+userId+"'";
			String insertUnSql = "insert into unregistereduser (USERID,AWSDEPID,AWSCOMPANYID,PHONE,NAME)VALUES(:USERID,:AWSDEPID,:AWSCOMPANYID,:PHONE,:NAME)";
			List<Map<String, Object>> depUnDepList = DBSql.query(queryCountSql, new ColumnMapRowMapper(),
					new Object[] {});
			if (depUnDepList.size() > 0) {
				continue;
			} else {
				Map<String, Object> paraMap = new HashMap<>();
				paraMap.put("USERID", userId);
				paraMap.put("AWSDEPID", depidAws);
				paraMap.put("AWSCOMPANYID", companyIdAws);
				paraMap.put("PHONE", phone);
				paraMap.put("NAME", username);
				DBSql.update(insertUnSql, paraMap);
			}
		}
		String delSql = "delete from WECHAT_USER t where t.COMPANYID='" + companyid_wechat
				+ "' and t.timeflag <" + lastTimeFlag;
		DBSql.update(delSql);
	}

	@Override
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		System.out.println("##########################Test!");
		String cfgstr = readToString(
				"E:\\Actionsoft\\bpm808\\bpm804\\apps\\install\\com.awspaas.user.apps.shhtaerospaceindustrial\\lib\\company.json");
		//String cfgstr=readToString("C:\\awsinst808test\\apps\\install\\com.awspaas.user.apps.shhtaerospaceindustrial\\lib\\company.json");
		long timeFlag = new Date().getTime();
		JSONArray companyArray = null;
		JSONObject jsonObject = JSON.parseObject(cfgstr);
		if (jsonObject != null) {
			// 取出按钮权限的数据
			companyArray = jsonObject.getJSONArray("companys");
		}
		Iterator<Object> num = companyArray.iterator();
		while (num.hasNext()) {
			JSONObject company = (JSONObject) num.next();
			String c_wechatid = (String) company.get("companywechatid");
			String c_secret = (String) company.get("companywechatseret");
			String c_awsid = (String) company.get("awsid");
			String role = (String) company.get("companyuserrole");
			WeChatUtil wechat = new WeChatUtil();

			String access_token = wechat.getAccessToken(c_wechatid, c_secret);

			List<Map<String, String>> depsWechat = wechat.getDepartmentList(access_token);

			List<WxUserInfo> wechatuserlist = wechat.getDepartmentUserDetails(depsWechat, access_token, "0");

			UpdateDepartments(depsWechat, c_awsid, c_wechatid, timeFlag);
			deleteUnRegisterDep(timeFlag, c_wechatid);
			updateUserTable(wechatuserlist, c_wechatid, timeFlag);
			deleteUnRegisterUser(timeFlag,c_wechatid);
		}

	}
}
